import { isIncludes, isObject } from './paramType';

let storage = window.localStorage;

function parse(key) {
    try {
      return JSON.parse(val);
    } catch (e) {
      return val;
    }
}

class Store {
    
    static get(key) {
        if (Array.isArray(key)) {
            return key.reduce((obj, item) => {
                obj[item] = this.get(item);
                return obj;
            }, {});
        }
        else {
            return parse(storage.getItem(key));
        }
    }
    static set(key, val) {
        if (isObject(key)) {
            for (let item in key) {
                this.set(item, key[item]);
            }
        } else {
            storage.setItem(key, isIncludes(val, ['Object', 'Array']) ? JSON.stringify(val) : val + '');
        }
    }

    static remove(key) {
        if (Array.isArray(key)) {
            for (let i = key.length - 1; i >= 0; i--) this.remove(key[i]);
        } else {
            storage.removeItem(key);
        }
    }

    static clear() {
        storage.clear();
    }

    static key() {
        return Object.keys(storage);
    }

    static all() {
        return this.get(this.key());
    }

    static length() {
        return this.key().length;
    }

    static has(key) {
        return this.get(key) === null ? false : true;
    }
}

export default Store;